import random
import string
import re
from tools.DBUtil import DBUtil

# 生成6位验证码
def generate_verification_code(length=6):
    # 定义验证码的字符集，包括数字和字母
    characters = string.ascii_letters + string.digits
    # 生成随机验证码
    verification_code = ''.join(random.choice(characters) for _ in range(length))
    return verification_code


# 验证邮箱格式
def is_valid_email(email):
    # 定义邮箱格式的正则表达式
    email_regex = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'
    # 使用正则表达式匹配邮箱地址
    if re.match(email_regex, email):
        return True
    else:
        return False

# 验证邮箱是否已注册
def is_valid_email_exist(email):
    if DBUtil.select_one("select * from user where oamail=%s", (email,)) is None:
        return False
    else:
        return True

# 验证用户名是否已注册或未在数据库中  
def is_valid_username_exist(username):
    if DBUtil.select_one("select * from user where username=%s and registertime is null", (username,)):
        return False
    else:
        return True

# 验证用户名是否已添加到数据库
def is_valid_user_exist(username):
    if DBUtil.select_one("select * from user where username=%s", (username,)) is None:
        return False
    else:
        return True
    
# 验证用户名和密码是否匹配
def is_correct_username_password(username, password):
    if DBUtil.select_one("select * from user where username=%s and passwd=%s", (username, password)) is None:
        return False
    else:
        return True

# 验证标识码是否存在
def is_valid_mark_code_exist(mark_code):
    if not mark_code:
        return True
    if DBUtil.select_one("select * from vm_list where markcode=%s", (mark_code,)) is None:
        return False
    else:
        return True
    
# 验证云虚拟机平台名称是否已存在
def is_valid_vsphere_exist(cloud_platform_name):
    if DBUtil.select_one("select * from config_vsphere where servername=%s", (cloud_platform_name,)) is None:
        return False
    else:    
        return True

# 验证组名称是否已存在
def is_valid_group_exist(group_name):
    if DBUtil.select_one("select * from config_group where groupname=%s", (group_name,)) is None:
        return False
    else:
        return True
    
